﻿using Client.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;

namespace Client.Hotfix
{
    public class Api : CSharpSingleton<Api>
    {
        private readonly Dictionary<int, object> ssms = new();

        public override void Awake()
        {
            UniApp.Instance.onUpdate += Tick;
            UniApp.Instance.onDesttroy += Destroy;
            Build();
            base.Awake();
        }

        public override void Destroy()
        {
            base.Destroy();
            ssms.Clear();
            UniApp.Instance.onUpdate -= Tick;
            UniApp.Instance.onDesttroy -= Destroy;
        }
        private void Build()
        {
            var targetAttribute = typeof(SSMAttribute);
            // 获取程序集
            Assembly assembly = AssemblyHelper.GetRunningAssembly("CHotFix");
            if (assembly == null)
            {
                return;
            }
            var typesWithAttribute = AssemblyHelper.GetAttribute4Assembly<SSMAttribute>("CHotFix");
            typesWithAttribute = typesWithAttribute.OrderBy(x => x.Attribute.Weight).ToList();


            foreach (var type in typesWithAttribute)
            {
                int hashcode = type.Type.GetHashCode();
                if (ssms.ContainsKey(hashcode))
                {
                    Debug.Log($"[ API ] - api 中已存在该服务/业务系统/玩法模式 : {type.Type.Name}");
                    continue;
                }
                var obj = Activator.CreateInstance(type.Type);

                ssms.Add(hashcode, obj);

                if (obj is IAwake awake)
                {
                    awakes.Add(awake);
                }

                if (obj is ITick tick)
                {
                    ticks.Add(tick);
                }

                if (obj is IDestroy destroy)
                {
                    destroys.Add(destroy);
                }
            }
        }

        public T Get<T>() where T : class, new()
        {
            int hashcode = typeof(T).GetHashCode();
            if (ssms.TryGetValue(hashcode, out var ssm))
            {
                return ssm as T;
            }
            else
            {
                Debug.Log($"[API] not exist ssm={typeof(T).Name}");
                return null;
            }
        }

    }

}
